import { useState, useEffect } from 'react'
import { Menu } from 'antd';
import { Asidelinks, nameToPathConfig, getOpenOneList, pathToConfig } from '@/router'
import { NAV_DEFAULT_ICON } from 'common/config';
import GetRouterInfo from 'components/GetRouterInfo';
/**
 * 根据路由信息生成React组件结构
 * @param {*} links 路由信息数组
 * @returns 
 */
function getMenuList(links) {
    return links.filter(it => !it.noAside).map((obj) => {
        const { config: { meta: { title, icon }, name }, child } = obj
        const Icon = icon || NAV_DEFAULT_ICON
        if (child && child.length) {
            const childElm = getMenuList(child)
            if (childElm.length) {
                return <Menu.SubMenu key={name} icon={<Icon />} title={title}>
                    {childElm}
                </Menu.SubMenu>
            }
        }
        return <Menu.Item key={name} icon={<Icon />}>{title}</Menu.Item>
    })
}

// 获取可以展开的导航集合
const { scope, map } = getOpenOneList()
const rootKeys = scope 
let history = null

/**
 * 基于 Ant Design 的导航菜单组件Menu 封装的 侧边栏导航
 * @returns 
 */
export default function AntdMenu(props = {}) {
    const { style = {} } = props
    const [open, setOpen] = useState([])
    const [select, setSelect] = useState([])
    let Links = getMenuList(Asidelinks)

    // 根据路由信息 展开导航栏 和选择导航栏
    useEffect(() => { 
        const {config, open} = pathToConfig(history.location.pathname) || {}
        if(!config) return
        setSelect([config.name]) // 选中处理 
        setOpen(open.slice(0, open.length - 1)) // 展开处理  
    }, [])

    // 展开处理
    const onOpenChange = keys => {
        const lastKey = keys.find(key => open.indexOf(key) === -1);
        if (!rootKeys.includes(lastKey)) {
            setOpen(keys);
        } else { 
            setOpen(lastKey ? map[lastKey] : []);
        }
    }

    // 点击处理
    let handleClick = e => {
        const config = nameToPathConfig(e.key)
        history && history.push(config.path) 
        setSelect([e.key])
    };

    return (
        <>
            <GetRouterInfo get={h => history = h} />
            <Menu
                onOpenChange={onOpenChange}
                onClick={handleClick}
                style={{ width: 255, ...style }}
                selectedKeys={select} 
                openKeys={open}
                mode="inline"
                theme="dark"
            >
                {Links}
            </Menu>
        </>
    )
}
